var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");

var divLoc={};
var dragging=false;
var drawingSurfaceImageData;
var mousedown;
var mousepose;
var polygons=[];
var polygonMulti
var polygonLine;
var polygonRect;
var polygonCircle;









$("#save").click(function(){
	save();
});
//text cursor
// function insertText(){
// 	divLoc.x=0;
// 	divLoc.y=0;
// 	saveDrawingSurface();
// 	function drawCursor(mousedown){
// 		context.fillRect(mousedown.x,mousedown.y,2,20);
// 		divLoc=mousedown;
// 		// console.log(mousedown.x+"mousedown"+mousedown.y);
// 		return divLoc;
// 	}
// 	function removeCursor(divLoc,drawingSurfaceImageData){
// 		context.putImageData(drawingSurfaceImageData,0,0,divLoc.x,divLoc.y,4,40);
// 		// context.clearRect(divLoc.x,divLoc.y,2,20);
// 		// console.log(divLoc.x+"y"+divLoc.y);
// 	}
// 	canvas.onmousedown=function(e){
// 		e.preventDefault();
// 		mousedown=getMousePos(canvas,e.clientX,e.clientY);
// 		// console.log("drawingSurfaceImageData"+drawingSurfaceImageData);
// 		removeCursor(divLoc,drawingSurfaceImageData);
// 		drawCursor(mousedown);

// 	}
// }
$("#text").click(function(){
	var tf=document.getElementById("tf");
	canvas.onmousedown=function(e){
    	mousedown=getMousePos(canvas,e.clientX,e.clientY);
    	e.preventDefault();
    // console.log(mousedown.x);
    	// tf.style.cssText="position:absolute;left:left+'px';top:50px;display:block";
    	tf.style.cssText="position:absolute;left:"+(mousedown.x+30)+"px;top:"+(mousedown.y+40)+"px;display:block;width:80px;height:50px";
    }
document.onkeydown=function(event){
    if(event.keyCode==13){

        tf.style.cssText="position:absolute;left:30px;top:50px;display:none";
        fillCanvas();
        tf.value="";
    }
}


//function
function fillCanvas(){
    var text=tf.value;
    var len=getTrueLength(text);
    //console.log(text);
    for(var i=0;i<len;i++){
        
        context.fillText(text,mousedown.x,mousedown.y);
    }
}

function getTrueLength(text){
    var length=text.length,trueLen=0;
    for(var x=0;x<length;x++){
        if(text.charCodeAt(x)>128){
            trueLen+=2;
        }else{
            trueLen+=1;
        }
        return trueLen;
    }
}

function getMousePos(canvas,X,Y){
    // canvas.addEventListener("mousedown",function(event){
    var box = canvas.getBoundingClientRect();
    return {
    x: X - box.left * (canvas.width / box.width),
    y: Y - box.top * (canvas.height / box.height)
    }
    // });
}
	// insertText();
});
	// context.fillStyle="blue";
	// context.font="20pt";
	// context.fillText("nihaosdg",canvas.width/2,canvas.height/2);
 //            // alert(mousePos.x);           
 //        });
	// var textArea=document.getElementById('text-area');

	// var textArea=document.createElement("textarea");
	// textArea.style.cssText="display:block";

	// var mousePos=getMousePos();
	
	// textArea.style.cssText="position:absolute;left:mousePos.x;top:mousePos.y;display:inline";
	
	  
	// writeTextOnCanvas(canvas, 22, 20, document.getElementById("text-area").value);
	// textArea.onkeyup = function(){
	// 	writeTextOnCanvas(canvas, 22, 20, this.value);
	// }


function saveDrawingSurface(){
	drawingSurfaceImageData=context.getImageData(0,0,canvas.width,canvas.height);
	// return drawingSurfaceImageData;
}	
function restoreDrawingSurface(){
	if(drawingSurfaceImageData){
		context.putImageData(drawingSurfaceImageData,0,0);
	}
	else{
		return null;
	}
	
}

// function drawPolygon(polygon){
// 	context.beginPath();
// 	polygon.createPath(context);
// 	polygon.stroke(context);
// }
	
	function chooseMove(x,y){
		// alert(chooseDiv.style.left);
		divLoc.left = x < divLoc.left ? x : divLoc.left;
		divLoc.top = y < divLoc.top ? y : divLoc.top;
		divLoc.width = Math.abs(x-divLoc.left);
		divLoc.height = Math.abs(y-divLoc.top);
		// chooseDiv.style.width=Math.abs(x+'px'-chooseDiv.style.left);
		// chooseDiv.style.height=Math.abs(y-chooseDiv.style.top)+'px';
		// alert(divLoc.width);
	}
	function chooseEnd(){

		chooseDiv.style.left=divLoc.left+'px';
		// alert("123"+chooseDiv.style.left);
		chooseDiv.style.top=divLoc.top;
		chooseDiv.style.width=divLoc.width+'px';
		chooseDiv.style.height=divLoc.height+'px';
		// alert(chooseDiv.style.top);
		context.strokeRect(divLoc.left,divLoc.top,divLoc.width,divLoc.height);
		// context.fillRect(200,200,100,100);
			// alert(chooseDiv.style.left);
			// context.drawImage(canvas,chooseDiv.style.left,chooseDiv.style.top,chooseDiv.style.width,chooseDiv.style.height);	
		
	}
	
$("#choose").click(function(){

	canvas.style.cursor='pointer';
	var draggingOffsetX;
	var draggingOffsetY;
	// var imgData={};
	// function drawPlogons(){
	// 	polygons.forEach(function(polygon){
	// 		drawPlogon(polygon);
	// 	});
	// }
	canvas.onmousedown=function(e){
		mousedown=getMousePos(canvas,e.clientX,e.clientY);
		e.preventDefault();
		
		polygons.forEach(function(polygon){			
			// polygon.createPath(context);
			// for (var i = 0; i < polygons.length; i++) {
			// 	console.log(polygons[i]);
			// }
			
			if (context.isPointInPath(mousedown.x,mousedown.y)) {
				saveDrawingSurface();
				// alert(polygon);
				// imgData=context.getImageData(0,0,canvas.width,canvas.height);
				dragging=polygon;
				// alert("here");
				// alert(polygon.x);
				// draggingOffsetX=mousedown.x-polygon.x;
				// draggingOffsetY=mousedown.y-polygon.y;
				// return;
			}
		});
		
	}

		canvas.onmousemove=function(e){
				// for (var item in dragging) {
				// 	console.log("the first:"+item+dragging[item]);
				// }
				
				if (dragging) {
					mousepose=getMousePos(canvas,e.clientX,e.clientY);
					e.preventDefault();
					// for (var item in dragging) {
					// 	draggingOffsetX=mousedown.x-dragging.x;
					// 	draggingOffsetY=mousedown.y-dragging.y;
					// 	dragging.x=mousepose.x-draggingOffsetX;
					// 	dragging.y=mousepose.y-draggingOffsetY;
					// }
					
					context.clearRect(0,0,canvas.width,canvas.height);
					// drawPlogons();
					// context.fillRect(20,20,20,20);
					for (var item in dragging) {
						// console.log("the second:"+item+dragging[item]);
						if (item=="pointX") {
							for (var item in dragging) {
								draggingOffsetX=mousedown.x-dragging.pointX;
								draggingOffsetY=mousedown.y-dragging.pointY;
								// console.log("x"+draggingOffsetX+"y"+draggingOffsetY);
								dragging.pointX=mousepose.x-draggingOffsetX;
								dragging.pointY=mousepose.y-draggingOffsetY;
								// console.log(dragging.pointX+"pointY"+dragging.pointY);
							}
							// console.log("x"+dragging.pointX+"y"+dragging.pointY+"radius"+dragging.radius);
							context.beginPath();
							context.arc(dragging.pointX,dragging.pointY,dragging.radius,0,2*Math.PI);
							
							context.stroke();
							dragging=false;
							// context.closePath();
							// console.log("drawCircle");
							break;
						}
						else if (item=="angle"){
							console.log("drawTriangle");
							break;
						}
						else if (item=="startX"){
							console.log("drawRect");
							break;
						}
						else{
							continue;
						}
					}
					// if (dragging==polygonMulti) {
					// 	drawTriangle();
					// }
					// else if (dragging==polygonLine) {
					// 	drawLine();
					// }
					// else if (dragging==polygonCircle) {
					// 	drawCircle();
					// }
					// else if (dragging==polygonRect) {
					// 	drawRect();
					// }
					// else{
					// 	// alert(JSON.stringify(dragging));
					// }
					// polygon(polygonMulti);
					// alert(e.target);
					
				}
				// restoreDrawingSurface();
				// drawLine(mousedown.x,mousedown.y,mousepose.x,mousepose.y);
			
		}
		canvas.onmouseup=function(e){
			dragging=false;
			// restoreDrawingSurface();
			// context.putImageData(imgData,0,0);
		}
	// canvas.style.cssText="cursor:crosshair";
	// var chooseDiv=document.getElementById("chooseDiv");
	// canvas.onmousedown=function (e){
	// 	var x=e.clientX;
	// 	var y=e.clientY;
	// 	e.preventDefault();
	// 	var mousedown=getMousePos(canvas,x,y);

	// 	chooseStart(mousedown.x,mousedown.y);
	// 	}
	// canvas.onmousemove=function(e){
	// 	if(dragging==true){
	// 		var x=e.clientX;
	// 		var y=e.clientY;
	// 		e.preventDefault();
	// 		var mousepose=getMousePos(canvas,x,y);
			
	// 		chooseMove(mousepose.x,mousepose.y);
	// 		// alert(mousepose.x);
	// 	}
		
	// }
	// canvas.onmouseup=function(e){
	// 	e.preventDefault();

	// 	chooseEnd();
	// 	dragging=false;
	// }
	// canvas.removeAllEventListener();
});
// function pencilDraw(){
// 	canvas.onmousedown=function(e){
// 		mousedown=getMousePos(canvas,e.clientX,e.clientY);
// 		e.preventDefault();
// 		divLoc=mousedown;
// 		dragging=true;
// 	}
// 	function drawShap(){
// 		context.save();
// 		context.beginPath();
// 			context.fillStyle="#ee0000";
// 			context.rect(mousepose.x,mousepose.y,2,2);
// 			context.closePath();
// 			context.fill();
// 			context.restore();
// 	}
// 	canvas.onmousemove=function(e){
// 		if (dragging) {
// 			context.save();
// 			mousepose=getMousePos(canvas,e.clientX,e.clientY);
// 			e.preventDefault();
// 			drawShap();	
// 		}
// 	}
// 	canvas.onmouseup=function(e){
// 		dragging=false;
// 	}
// }
function drawPencil(){
	// var lineParam;
	canvas.onmousedown=function(e){
		mousedown=getMousePos(canvas,e.clientX,e.clientY);
		e.preventDefault();
		divLoc=mousedown;
		dragging=true;
		
	}
	function drawLine(xStart,yStart,x,y){
		context.save();
		context.beginPath();
		context.moveTo(xStart,yStart);
		context.lineTo(x,y);
		context.stroke();
		context.restore();
		}
		canvas.onmousemove=function(e){
			if (dragging) {
				e.preventDefault();
				var mousepose=getMousePos(canvas,e.clientX,e.clientY);
				// restoreDrawingSurface();
				drawLine(divLoc.x,divLoc.y,mousepose.x,mousepose.y);
				divLoc=mousepose;
			}
		}
		canvas.onmouseup=function(e){
			var mousepose=getMousePos(canvas,e.clientX,e.clientY);
			e.preventDefault();
			// restoreDrawingSurface();
			// lineParam= new polygonLine(mousedown.x,mousedown.y,mousepose.x,mousepose.y);
			// drawLine(divLoc.x,divLoc.y,mousepose.x,mousepose.y);
			dragging=false;
			
			// polygons.push(lineParam);
			// console.log(polygonLine);
		}
}
$("#pencil").click(function(){
	canvas.style.cursor="crosshair";
	drawPencil();
});
polygonLine=function(xStart,yStart,x,y){
	this.xStart=xStart;
	this.yStart=yStart;
	this.x=x;
	this.y=y;
};
function drawLine(){
	var lineParam;
	canvas.onmousedown=function(e){
		mousedown=getMousePos(canvas,e.clientX,e.clientY);
		e.preventDefault();
		saveDrawingSurface();
		dragging=true;
		
	}
	function drawLine(xStart,yStart,x,y){
		
		context.beginPath();
				context.moveTo(xStart,yStart);
				context.lineTo(x,y);
				context.stroke();
		}
		canvas.onmousemove=function(e){
			if (dragging) {
				e.preventDefault();
				var mousepose=getMousePos(canvas,e.clientX,e.clientY);
				restoreDrawingSurface();
				drawLine(mousedown.x,mousedown.y,mousepose.x,mousepose.y);
			}
		}
		canvas.onmouseup=function(e){
			var mousepose=getMousePos(canvas,e.clientX,e.clientY);
			e.preventDefault();
			restoreDrawingSurface();
			lineParam= new polygonLine(mousedown.x,mousedown.y,mousepose.x,mousepose.y);
			drawLine(mousedown.x,mousedown.y,mousepose.x,mousepose.y);
			dragging=false;
			polygons.push(lineParam);
			// console.log(polygonLine);
		}
}
$("#line").click(function(){
	// canvas.onmousedown=function(e){
	// 	var x=e.clientX;
	// 	var y=e.clientY;
	// 	e.preventDefault();
	// 	var mousedown=getMousePos(canvas,x,y);
	// 	chooseStart(mousedown.x,mousedown.y);
	// }
	// canvas.onmouseup=function(e){
		
	// 	var x=e.clientX;
	// 	var y=e.clientY;
	// 	e.preventDefault();
	// 	var mousepose=getMousePos(canvas,x,y);
	// 	context.beginPath();
	// 	context.moveTo(divLoc.left,divLoc.top);
	// 	context.lineTo(mousepose.x,mousepose.y);
	// 	context.closePath();
	// 	context.stroke();
	// }
	drawLine();
});
$("#curve").click(function(){
	
});
$("#zhexian").click(function(){
	
});

function drawCircle(){
	var x1,x2,y1,y2,circleParam;
	polygonCircle=function(pointX,pointY,radius){
	this.pointX=pointX;
	this.pointY=pointY;
	this.radius=radius;
	};
	
	canvas.onmousedown=function(e){
		var x=e.clientX;
		var y=e.clientY;
		e.preventDefault();
		var mousedown=getMousePos(canvas,x,y);
		x1=mousedown.x;
		y1=mousedown.y;
	}
	canvas.onmouseup=function(e){
		
		var x=e.clientX;
		var y=e.clientY;
		e.preventDefault();
		var mousepose=getMousePos(canvas,x,y);
		x2=mousepose.x;
		y2=mousepose.y;
		var pointX=(x1+x2)/2;
		// console.log("x1:"+x1+"x2:"+x2+"pointX:"+pointX);

		var pointY=(y1+y2)/2;
		// console.log("y1:"+y1+"x2:"+y2+"pointX:"+pointY);
		var radius=Math.sqrt((y2-y1)*(y2-y1)+(x2-x1)*(x2-x1))/2;
		// console.log(radius);
		
		context.beginPath();
		context.arc(pointX,pointY,radius,0,2*Math.PI);
		circleParam=new polygonCircle(pointX,pointY,radius);
		context.closePath();
		context.stroke();
		// console.log(circle);
		polygons.push(circleParam);
		// for (var i = 0; i < polygons.length; i++) {
		// 	console.log(polygons[i]);
		// }

		
	}
}
$("#circle").click(function(){
	drawCircle();
});

function drawTriangle(){
	var x1,x2,y1,y2,pointX,pointY,radius,sides,angle,triangleParam;
	polygonMulti=function(x,y,radius,angle,sides){
	this.x=x;
	this.y=y;
	this.radius=radius;
	this.angle=angle;
	this.sides=sides;
	};
	var Point=function(x,y){
		this.x=x;
		this.y=y;
	};
	canvas.onmousedown=function (e){
		e.preventDefault();
		mousedown=getMousePos(canvas,e.clientX,e.clientY);
		x1=mousedown.x;
		y1=mousedown.y;
		}
	function polygon(x,y,radius,angle,sides){
		// var angle=this.angle;
		var points=[];
		for (var i = 0; i < sides; i++) {
			points.push(new Point(x+radius*Math.sin(angle),y-radius*Math.cos(angle)));
			angle+=2*Math.PI/sides;
		}
		
		context.beginPath();
		context.moveTo(points[0].x,points[0].y);
		for (var i = 0; i < sides; i++) {
			context.lineTo(points[i].x,points[i].y);
		}
		context.closePath();
		context.stroke();
	}
	
	
	canvas.onmouseup=function(e){
		mousepose=getMousePos(canvas,e.clientX,e.clientY);
		e.preventDefault();
		x2=mousepose.x;
		y2=mousepose.y;
		pointX=(x1+x2)/2;
		pointY=(y1+y2)/2;
		angle=0;
		sides=6;
		radius=Math.sqrt((y2-y1)*(y2-y1)+(x2-x1)*(x2-x1))/2;
		triangleParam=new polygonMulti(pointX,pointY,radius,angle,sides);
		polygons.push(triangleParam);
		// polygon(pointX,pointY,radius,0,6);
		polygon(pointX,pointY,radius,angle,sides);
	}
}
$("#triangle").click(function(){
	drawTriangle();
});

function drawRect(){
	var rectParam;
	var polygonRect=function(startX,startY,endX,endY){
		this.startX=startX;
		this.startY=startY;
		this.endX=endX;
		this.endY=endY;
	};
	canvas.onmousedown=function (e){
		var x=e.clientX;
		var y=e.clientY;
		e.preventDefault();
		var mousedown=getMousePos(canvas,x,y);
		divLoc.left=mousedown.x;
		divLoc.top=mousedown.y;
		// dragging=true;
		// chooseStart(mousedown.x,mousedown.y);
		}
	// canvas.onmousemove=function(e){
	// 	if(dragging==true){
	// 		var x=e.clientX;
	// 		var y=e.clientY;
	// 		e.preventDefault();
	// 		var mousepose=getMousePos(canvas,x,y);
			
	// 		chooseMove(mousepose.x,mousepose.y);
	// 		// alert(mousepose.x);
	// 	}
		
	// }
	canvas.onmouseup=function(e){
		mousepose=getMousePos(canvas,e.clientX,e.clientY);
		e.preventDefault();

		// mousedown.x=mousepose.x<mousedown.x?mousepose.x:mousedown.x;
		// mousedown.y=mousepose.y<mousepose.y?mousepose.y:mousedown.y;
		divLoc.left = mousepose.x < divLoc.left ? mousepose.x : divLoc.left;
		divLoc.top = mousepose.y < divLoc.top ? mousepose.y : divLoc.top;
		divLoc.width = Math.abs(mousepose.x-divLoc.left);
		divLoc.height = Math.abs(mousepose.y-divLoc.top);

		rectParam=new polygonRect(divLoc.left,divLoc.top,divLoc.width,divLoc.height);
		polygons.push(rectParam);
		context.beginPath();
		context.rect(divLoc.left,divLoc.top,divLoc.width,divLoc.height);
		context.closePath();
		context.stroke();
	}
	// $("#rect").unbind("click");
}
$("#rect").click(function(){
	// canvas.removeEventListener("click");
	// var text=$("#font-family option:selected").text();
	// var value=$("font-family option:selected").val();
	// var font=document.getElementById("font-family").value();
	// var value=document.all.font.value();
	// context.font=
	// context.strokeRect();
	drawRect();
});
function erase(){
	canvas.onmousedown=function(e){
		mousedown=getMousePos(canvas,e.clientX,e.clientY);
		e.preventDefault();
		divLoc=mousedown;
		dragging=true;
	}
	function eraseLast(divLoc){
		context.save();
		context.beginPath();
			// context.arc(mousedown.x,mousedown.y,30,0,2*Math.PI,false);
			// context.stroke();
			context.fillStyle="#efefef";
			context.arc(divLoc.x,divLoc.y,35,0,2*Math.PI,false);
			context.closePath();
			context.fill();
			// context.stroke();
			context.clip();
			context.restore();
	}
	function drawShap(){
		context.save();
		context.beginPath();
			// context.arc(mousedown.x,mousedown.y,30,0,2*Math.PI,false);
			// context.stroke();
			context.fillStyle="#ee0000";
			context.arc(mousepose.x,mousepose.y,30,0,2*Math.PI,false);
			context.closePath();
			context.fill();
			// context.stroke();
			// context.clip();
			context.restore();
	}
	canvas.onmousemove=function(e){
		if (dragging) {
			context.save();
			mousepose=getMousePos(canvas,e.clientX,e.clientY);
			e.preventDefault();
			eraseLast(divLoc);
			drawShap();	
		}
		divLoc=mousepose;
	}
	canvas.onmouseup=function(e){
		eraseLast(divLoc);
		dragging=false;
		// context.restore();
	}
}
$("#erase").click(function(){
	erase();
});
$("#color").click(function(){

});
$("#trash").click(function(){
	context.clearRect(0,0,context.canvas.width,context.canvas.height);
});
function save(){
	var image = new Image();
	var dataURL = this.canvas.toDataURL("image/png");
	dataURL = dataURL.replace("image/png", "image/octet-stream");
	document.location.href = dataURL;
}


	function writeTextOnCanvas(canvas, lh, rw, text){
		var ctx = canvas.getContext("2d");
		var lineheight = lh;
		var text = text;

		ctx.width = canvas.width;
		ctx.height = canvas.height;

		// ctx.clearRect(0, 0, ctx.width, ctx.height);
		ctx.font = "10px 微软雅黑";
		ctx.fillStyle = "#f00";
		function getTrueLength(str){//获取字符串的真实长度（字节长度）
			var len = str.length, truelen = 0;
			for(var x = 0; x < len; x++){
				if(str.charCodeAt(x) > 128){
					truelen += 2;
				}else{
					truelen += 1;
				}
			}
			return truelen;
		}
		function cutString(str, leng){//按字节长度截取字符串，返回substr截取位置
			var len = str.length, tlen = len, nlen = 0;
			for(var x = 0; x < len; x++){
				if(str.charCodeAt(x) > 128){
					if(nlen + 2 < leng){
						nlen += 2;
					}else{
						tlen = x;
						break;
					}
				}else{
					if(nlen + 1 < leng){
						nlen += 1;
					}else{
						tlen = x;
						break;
					}
				}
			}
			return tlen;
		}
		for(var i = 1; getTrueLength(text) > 0; i++){
			var tl = cutString(text, rw);
			ctx.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), 10, i * lineheight + 50);
			text = text.substr(tl);
		}
	}


function getMousePos(canvas,X,Y){
	// canvas.addEventListener("mousedown",function(event){
	var box = canvas.getBoundingClientRect();
    return { 
     x: X - box.left * (canvas.width / box.width),
     y: Y - box.top * (canvas.height / box.height)
    }
	// });
}

// function location(){
// 	var canvasOffset = $(canvas).offset();
//     var canvasX = Math.floor(e.pageX - canvasOffset.left);
//     var canvasY = Math.floor(e.pageY - canvasOffset.top);
//     alert(canvasX);
//     return canvasX,canvasY;
// }



// function newText(){
//     var textfield = $("#text-area");
//     scene.addEventListener("dbclick",function(event){
//                 if(event.target == null) alert(event.target); return;
                
//                 // var e = event.target;
//                 textfield.css({
//                     top: event.pageY,
//                     left: event.pageX - e.width/2
//                 }).show().attr('value', e.text).focus().select();
//                 e.text = "";
//                 textfield[0].JTopoNode = e;
//             });
            
//             $("#text-area").blur(function(){
//                 textfield[0].JTopoNode.text = textfield.hide().val();
//             });
//         }

